<template>
  <div>
    <div class="category-params-content">
      <el-divider>参数信息</el-divider>
      <!-- 类别和参数区域 -->
      <div v-if="categories && categories.length > 0">
        <el-collapse v-model="activeCollapse">
          <draggable
            v-model="categories"
            handle=".category-drag-handle"
            animation="300"
            @end="handleCategoryReorder"
          >
            <el-collapse-item
              v-for="(category, cIndex) in categories"
              :key="category.id || category.tempId"
              :title="category.name || '未命名类别'"
              :name="category.id || category.tempId"
            >
              <template slot="title">
                <span class="category-drag-handle"><i class="el-icon-d-caret" /></span>
                <span>{{ category.name || '未命名类别' }}</span>
                <span class="category-position">(排序: {{ category.position || cIndex + 1 }})</span>
                <el-tag v-if="category.is_shown === false" type="danger" size="mini" style="margin-left: 5px;">已隐藏</el-tag>
              </template>
              <div class="category-container" style="margin-bottom: 15px">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="form-item">
                      <el-autocomplete
                        v-model="category.name"
                        class="inline-input"
                        clearable
                        :fetch-suggestions="querySearchCategory"
                        placeholder="请输入类别名称"
                        style="width: 100%"
                        @select="handleSelectCategory"
                      />
                    </div>
                  </el-col>
                  <el-col :span="16">
                    <el-button v-if="objectId && !readOnly" type="success" size="mini" icon="el-icon-check" :loading="categoryLoading" @click="handleSaveCategory(category)">保存类别</el-button>
                    <el-button v-if="!readOnly" type="danger" size="mini" icon="el-icon-delete" @click="handleDeleteCategory(category, cIndex)">删除类别</el-button>
                    <el-switch
                      v-model="category.is_shown"
                      active-text="显示"
                      inactive-text="隐藏"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      :disabled="readOnly"
                      style="margin-left: 10px;"
                      @change="handleCategoryVisibilityChange(category)"
                    />
                    <el-button
                      v-if="!readOnly"
                      type="primary"
                      size="mini"
                      icon="el-icon-plus"
                      style="margin-left: 10px;"
                      @click="handleAddParameterAndShow(category)"
                    >
                      添加参数
                    </el-button>
                  </el-col>
                </el-row>

                <!-- 类别图片上传区域 -->
                <div style="margin-bottom: 15px">
                  <span>类别图片：</span>
                  <div class="upload-container">
                    <!-- 粘贴上传区域 -->
                    <div v-loading="category.imageLoading" class="paste-area" tabindex="0" @paste="handlePaste($event, category)" @click="focusPasteArea($event)" @dragover.prevent @drop="handleDrop($event, category)">
                      <div v-if="!category.images || !category.images.length" class="paste-tip">
                        <i class="el-icon-picture-outline" />
                        <div>选择本框，直接粘贴图片</div>
                      </div>
                      <div v-else class="paste-images">
                        <div v-for="(img, index) in category.images" :key="index" class="image-item">
                          <img :src="img" class="preview-image" @click.stop="previewImage(img)">
                          <i class="el-icon-delete delete-icon" @click.stop="removeCategoryImage(category, index)" />
                          <div v-if="showAI" class="image-ai-button">
                            <AITask
                              show_name="AI提取图片要点"
                              task-name="task_productionimage_info"
                              :params="{image_url: img}"
                              button-text="AI分析"
                              button-type="primary"
                              size="mini"
                              button-icon="el-icon-s-opportunity"
                              dialog-title="图片内容分析"
                              :show-icon="true"
                              title="AI分析图片"
                              @apply="(result) => handleApplyAIResult(result, category)"
                            />
                          </div>
                        </div>
                      </div>
                    </div>

                    <input
                      :ref="`fileInput_${category.id || category.tempId}`"
                      type="file"
                      style="display: none"
                      accept="image/*"
                      multiple
                      @change="handleFileChange($event, category)"
                    >
                  </div>
                  <el-dialog :visible.sync="dialogImageVisible" append-to-body>
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </div>

                <!-- 参数列表 -->
                <el-table
                  v-show="shouldShowParameters(category)"
                  :data="category.parameters || []"
                  border
                  style="width: 100%"
                  class="parameters-table"
                >
                  <el-table-column prop="name" label="参数名称" width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.name" placeholder="参数名称" :readonly="readOnly" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="value" label="参数值">
                    <template slot-scope="scope">
                      <div class="markdown-input-container">
                        <div v-if="scope.row.value && isMarkdown(scope.row.value)" class="markdown-preview-container">
                          <v-md-editor v-model="scope.row.value" mode="preview" height="120px" />
                          <i class="el-icon-edit-outline markdown-icon" title="Markdown编辑器" @click="openMarkdownEditor(scope.row)" />
                        </div>
                        <template v-else>
                          <el-input
                            v-model="scope.row.value"
                            type="textarea"
                            :rows="3"
                            placeholder="支持多行输入，可用markdown语法"
                            clearable
                            :readonly="readOnly"
                          />
                          <i v-if="!readOnly" class="el-icon-edit-outline markdown-icon" title="Markdown编辑器" @click="openMarkdownEditor(scope.row)" />
                        </template>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="配置信息" width="280">
                    <template slot-scope="scope">
                      <div style="display: flex; flex-direction: column; gap: 8px;">
                        <div style="display: flex; align-items: center; gap: 8px;">
                          <span style="font-size: 12px; color: #606266; width: 40px;">颜色:</span>
                          <el-color-picker v-model="scope.row.color" size="mini" />
                        </div>
                        <div style="display: flex; align-items: center; gap: 8px;">
                          <span style="font-size: 12px; color: #606266; width: 40px;">数量:</span>
                          <el-input v-model="scope.row.unit" placeholder="数量单位" size="mini" style="flex: 1;" />
                        </div>
                        <div style="display: flex; align-items: center; gap: 8px;">
                          <span style="font-size: 12px; color: #606266; width: 40px;">价格:</span>
                          <el-input v-model="scope.row.price" placeholder="0.00" size="mini" style="flex: 1;" type="number" step="0.01" />
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="图片" width="300">
                    <template slot-scope="scope">
                      <!-- 粘贴上传区域 -->
                      <div v-loading="scope.row.imageLoading" class="paste-area parameter-paste-area" tabindex="0" @paste="handleParameterPaste($event, scope.row)" @click="focusPasteArea($event)" @dragover.prevent @drop="handleParameterDrop($event, scope.row)">
                        <div v-if="!scope.row.images || !scope.row.images.length" class="paste-tip">
                          <i class="el-icon-picture-outline" />
                          <div>粘贴或拖拽图片</div>
                        </div>
                        <div v-else class="paste-images parameter-images">
                          <div v-for="(img, index) in scope.row.images" :key="index" class="parameter-image-item">
                            <img :src="img" class="preview-image" @click.stop="previewImage(img)">
                            <i class="el-icon-delete delete-icon" @click.stop="removeParameterImage(scope.row, index)" />
                            <div v-if="showAI" class="image-ai-button">
                              <AITask
                                show_name="提取要点"
                                task-name="task_productionimage_info"
                                :params="{image_url: img}"
                                button-text="AI分析"
                                button-type="primary"
                                size="mini"
                                button-icon="el-icon-s-opportunity"
                                dialog-title="图片内容分析"
                                :show-icon="true"
                                title="AI分析图片"
                                @apply="(result) => handleApplyParameterAIResult(result, scope.row)"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                      <input
                        :ref="`paramFileInput_${scope.row.id || scope.$index}`"
                        type="file"
                        style="display: none"
                        accept="image/*"
                        multiple
                        @change="handleParameterFileChange($event, scope.row)"
                      >
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                      <el-button v-if="objectId" type="success" size="mini" icon="el-icon-check" :loading="parameterLoading" @click="handleSaveParameter(category, scope.row)">保存</el-button>
                      <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDeleteParameter(category, scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 底部添加参数按钮 -->
                <div v-show="shouldShowParameters(category)" class="bottom-add-button">
                  <el-button type="primary" size="mini" icon="el-icon-plus" style="margin-top: 10px" @click="handleAddParameter(category)">
                    添加参数
                  </el-button>
                </div>
              </div>
            </el-collapse-item>
          </draggable>
        </el-collapse>
        <!-- 底部添加类别按钮 -->
        <div class="bottom-add-category">
          <el-button type="primary" icon="el-icon-plus" style="margin-top: 15px" @click="handleAddCategory">
            添加类别
          </el-button>
        </div>
      </div>
      <div v-else style="text-align: center; margin-top: 30px; padding: 40px 0;">
        <div style="color: #909399; font-size: 14px; margin-bottom: 20px;">
          <i class="el-icon-folder-opened" style="font-size: 48px; display: block; margin-bottom: 10px; color: #c0c4cc;" />
          暂无类别信息
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddCategory">添加类别</el-button>
      </div>
    </div>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- Markdown编辑对话框 -->
    <el-dialog
      title="Markdown编辑器"
      :visible.sync="markdownDialogVisible"
      width="80%"
      :before-close="closeMarkdownDialog"
      append-to-body
      custom-class="markdown-dialog"
    >
      <v-md-editor
        v-model="currentMarkdownContent"
        height="450px"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMarkdownDialog">取消</el-button>
        <el-button type="primary" @click="confirmMarkdownEdit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Post as PostCategory, Put as PutCategory, Delete as DeleteCategory, GetForModel, Reorder } from '@/api/crm/crmcommoncategory'
import { Post as PostParameter, Put as PutParameter, Delete as DeleteParameter, GetParametersByCategory } from '@/api/crm/crmcommonparameter'
import { Post as UploadBase64Image } from '@/api/cms/image'
import draggable from 'vuedraggable'
import AITask from '@/components/AITask'

export default {
  name: 'CommonCategoryParams',
  components: { draggable, AITask },
  props: {
    modelType: {
      type: String,
      required: true,
      default: 'crmpaymentfile'
    },
    objectId: {
      type: [Number, String],
      default: null
    },
    visible: {
      type: Boolean,
      default: true
    },
    uploadDirectory: {
      type: Number,
      default: -1
    },
    uploadKeyword: {
      type: String,
      default: ''
    },
    showAI: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    defaultCategoryNames: {
      type: Array,
      default: () => []
    },
    showParametersByDefault: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      categories: [],
      categoryOptions: [
        { value: '需求要点' },
        { value: '版型图' },
        { value: '数量' },
        { value: '面料' },
        { value: 'logo' },
        { value: '辅料' },
        { value: '特殊要求' }
      ],
      paramsOptions: [
        { value: '尺寸' },
        { value: '颜色' },
        { value: '成分' },
        { value: '克重' }
      ],
      loading: false,
      categoryLoading: false,
      parameterLoading: false,
      activeCollapse: [], // 当前展开的折叠面板
      dialogImageUrl: '',
      dialogImageVisible: false,
      // Markdown编辑相关
      markdownDialogVisible: false,
      currentMarkdownContent: '',
      currentEditingParameter: null,
      saveParamTimeout: null,
      // 控制每个类别参数列表的显示状态
      categoryParametersVisible: {}
    }
  },

  watch: {
    objectId: {
      handler(val) {
        console.log('objectId changed:', val)
        if (val) {
          this.loadCategoriesAndParameters()
        } else {
          this.categories = []
        }
      },
      immediate: true
    },
    visible: {
      handler(val) {
        if (val && this.objectId) {
          // 延迟一下再刷新图片
          setTimeout(() => {
            this.refreshImages()
          }, 500)
        }
      },
      immediate: true
    }
  },
  created() {
    // 发射组件初始化事件
    this.$emit('component-initialized')
  },
  mounted() {
    // 初始化所有类别和参数的imageLoading状态为false
    if (this.categories && this.categories.length > 0) {
      this.categories.forEach(category => {
        this.$set(category, 'imageLoading', false)

        if (category.parameters) {
          category.parameters.forEach(param => {
            this.$set(param, 'imageLoading', false)
          })
        }
      })
    }
  },
  // 在组件销毁前清理定时器
  beforeDestroy() {
    // 清理任何可能存在的定时器
    if (this.saveParamTimeout) {
      clearTimeout(this.saveParamTimeout)
    }
  },
  methods: {
    // 加载类别和参数数据
    async loadCategoriesAndParameters() {
      if (!this.objectId) {
        console.log('没有对象ID，清空类别数据')
        this.categories = []
        return
      }

      try {
        console.log('开始加载类别和参数数据，模型类型:', this.modelType, '对象ID:', this.objectId)
        this.loading = true

        // 使用新的通用API获取类别数据
        const categoriesResponse = await GetForModel(this.modelType, this.objectId)
        console.log('获取到类别数据:', categoriesResponse.data)

        if (categoriesResponse.data && categoriesResponse.data.length > 0) {
          // 为每个类别获取其参数
          const categoriesWithParams = await Promise.all(
            categoriesResponse.data.map(async(category) => {
              try {
                // 获取该类别下的参数
                const paramsResponse = await GetParametersByCategory(category.id)
                console.log(`类别 ${category.name} 的参数:`, paramsResponse.data)

                // 处理类别图片
                let categoryImages = category.images || ''
                if (typeof categoryImages === 'string') {
                  categoryImages = categoryImages.split(',').filter(url => url.trim() !== '')
                }

                // 处理参数数据
                const parameters = (paramsResponse.data || []).map(param => ({
                  ...param,
                  images: typeof param.images === 'string'
                    ? param.images.split(',').filter(url => url.trim() !== '')
                    : param.images || []
                }))

                return {
                  ...category,
                  images: categoryImages,
                  parameters: parameters
                }
              } catch (error) {
                console.error(`获取类别 ${category.name} 的参数失败:`, error)
                return {
                  ...category,
                  images: typeof category.images === 'string'
                    ? category.images.split(',').filter(url => url.trim() !== '')
                    : category.images || [],
                  parameters: []
                }
              }
            })
          )

          this.categories = categoriesWithParams
        } else {
          this.categories = []
        }

        // 无论是否有现有分类，都检查是否需要添加缺失的默认分类
        if (this.defaultCategoryNames && this.defaultCategoryNames.length > 0) {
          // 延迟一点执行，确保现有分类数据已经完全加载
          setTimeout(() => {
            this.createDefaultCategories()
          }, 200)
        }

        // 使用$nextTick确保DOM已更新
        this.$nextTick(() => {
          // 设置初始展开的面板
          this.activeCollapse = this.categories.map(cat => cat.id || cat.tempId)
          // 刷新图片显示
          this.refreshImages()
        })

        // 延迟一点关闭loading状态，避免闪烁
        setTimeout(() => {
          this.loading = false
        }, 300)
      } catch (error) {
        console.error('加载类别和参数数据失败:', error)
        // 如果加载失败，至少要设置基本数据
        this.categories = []
        this.loading = false

        this.$notify.error({
          title: '错误',
          message: '加载类别和参数数据失败: ' + (error.message || '未知错误')
        })
      }
    },

    // 创建默认分类
    createDefaultCategories() {
      console.log('创建默认分类:', this.defaultCategoryNames)

      if (!this.defaultCategoryNames || this.defaultCategoryNames.length === 0) {
        console.log('没有默认分类可创建')
        return
      }

      // 获取当前已存在的分类名称列表
      const existingCategoryNames = (this.categories || []).map(cat => cat.name)
      console.log('现有分类名称:', existingCategoryNames)

      // 筛选出需要添加的默认分类（排除已存在的）
      const missingCategories = this.defaultCategoryNames.filter(defaultName =>
        !existingCategoryNames.includes(defaultName)
      )

      console.log('需要添加的默认分类:', missingCategories)

      if (missingCategories.length === 0) {
        this.$message.info('所有默认分类都已存在，无需重复创建')
        return
      }

      // 计算最大position值，确保新分类排在最后
      let maxPosition = 0
      if (this.categories && this.categories.length > 0) {
        maxPosition = Math.max(...this.categories.map(cat => cat.position || 0))
      }

      const newCategories = []
      missingCategories.forEach((categoryName, index) => {
        const newCategory = {
          name: categoryName,
          tempId: `default-cat-${index}-${Date.now()}`, // 临时ID用于界面展示
          parameters: [],
          images: [],
          position: maxPosition + index + 1, // 设置排序位置，排在现有分类之后
          is_shown: true // 默认为显示
        }

        this.categories.push(newCategory)
        newCategories.push(newCategory)
      })

      // 使用$nextTick确保DOM已更新
      this.$nextTick(() => {
        // 设置新添加的分类为展开状态
        const newTempIds = newCategories.map(cat => cat.tempId)
        if (!this.activeCollapse) {
          this.activeCollapse = []
        }
        this.activeCollapse = [...this.activeCollapse, ...newTempIds]

        this.$notify({
          title: '提示',
          message: `已添加 ${missingCategories.length} 个缺失的默认分类`,
          type: 'success',
          duration: 2000
        })

        // 发射默认分类创建事件
        this.$emit('default-categories-created', newCategories)
      })
    },

    // 公开方法：手动创建默认分类
    createDefaultCategoriesManually() {
      return this.createDefaultCategories()
    },

    // 刷新图片显示
    refreshImages() {
      this.$nextTick(() => {
        // 强制浏览器重新加载图片
        const images = document.querySelectorAll('.preview-image')
        images.forEach(img => {
          const originalSrc = img.src
          if (originalSrc) {
            // 添加时间戳强制刷新缓存
            img.src = originalSrc.includes('?')
              ? originalSrc + '&_t=' + new Date().getTime()
              : originalSrc + '?_t=' + new Date().getTime()
          }
        })
        console.log('已刷新', images.length, '张图片')
      })
    },

    // 添加新类别
    handleAddCategory() {
      if (!this.categories) {
        this.categories = []
      }

      // 计算最大position值
      let maxPosition = 0
      if (this.categories.length > 0) {
        maxPosition = Math.max(...this.categories.map(cat => cat.position || 0))
      }

      const newCategory = {
        name: '新类别',
        tempId: 'new-cat-' + Date.now(), // 临时ID用于界面展示
        parameters: [],
        images: [],
        position: maxPosition + 1, // 设置为当前最大position + 1
        is_shown: true // 默认为显示
      }

      // 如果不是默认显示参数列表，设置新类别的参数列表初始状态为隐藏
      if (!this.showParametersByDefault) {
        this.$set(this.categoryParametersVisible, newCategory.tempId, false)
      }

      this.categories.push(newCategory)

      // 确保新类别被展开 - 使用$nextTick确保DOM已更新
      this.$nextTick(() => {
        // 保留当前展开项，同时添加新类别到展开列表
        if (!this.activeCollapse) {
          this.activeCollapse = []
        }
        this.activeCollapse = [...this.activeCollapse, newCategory.tempId]

        // 滚动到新添加的类别位置
        setTimeout(() => {
          const element = document.querySelector(`[name="${newCategory.tempId}"]`)
          if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'center' })
          }
        }, 100)
      })

      // 发射添加类别事件
      this.$emit('category-added', newCategory)
    },

    // 删除类别
    handleDeleteCategory(category, index) {
      this.$confirm('确认删除该类别?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (category.id) {
          // 已保存到数据库的类别，需要通过API删除
          this.categoryLoading = true
          DeleteCategory(category.id).then(() => {
            this.categories.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '类别删除成功',
              type: 'success'
            })
            this.categoryLoading = false
            // 发射删除事件
            this.$emit('category-deleted', category)
          }).catch(error => {
            console.error('删除类别失败', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '删除类别失败'
            })
          })
        } else {
          // 未保存到数据库的类别，直接从内存中删除
          this.categories.splice(index, 1)
          // 发射删除事件
          this.$emit('category-deleted', category)
        }
      }).catch(() => {
        // 取消删除
      })
    },

    // 添加参数
    handleAddParameter(category) {
      if (!category.parameters) {
        category.parameters = []
      }

      category.parameters.push({
        name: '',
        value: '',
        color: '#000000',
        unit: '',
        price: 0.0,
        crmproduction_order_category: category.id,
        images: []
      })
    },

    // 添加参数并显示参数列表
    handleAddParameterAndShow(category) {
      // 设置该类别的参数列表为可见
      this.$set(this.categoryParametersVisible, category.id || category.tempId, true)

      // 添加新参数
      this.handleAddParameter(category)

      console.log('显示参数列表并添加参数:', category.name)
    },

    // 判断是否应该显示参数列表
    shouldShowParameters(category) {
      const categoryKey = category.id || category.tempId

      // 如果设置了默认显示参数列表，则始终显示
      if (this.showParametersByDefault) {
        return true
      }

      // 如果有参数存在或者用户手动显示了参数列表，则显示
      return (category.parameters && category.parameters.length > 0) ||
             this.categoryParametersVisible[categoryKey]
    },

    // 删除参数
    handleDeleteParameter(category, paramIndex) {
      this.$confirm('确认删除该参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = category.parameters[paramIndex]

        if (param.id) {
          // 已保存到数据库的参数，需要通过API删除
          this.parameterLoading = true
          DeleteParameter(param.id).then(() => {
            category.parameters.splice(paramIndex, 1)
            this.$notify({
              title: '成功',
              message: '参数删除成功',
              type: 'success'
            })
            this.parameterLoading = false
          }).catch(error => {
            console.error('删除参数失败', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '删除参数失败'
            })
          })
        } else {
          // 未保存到数据库的参数，直接从内存中删除
          category.parameters.splice(paramIndex, 1)
        }
      }).catch(() => {
        // 取消删除
      })
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    // 类别图片上传成功
    handleCategoryUploadSuccess(response, category) {
      if (!category.images) {
        category.images = []
      }
      category.images.push(response.url)
    },

    // 类别图片删除
    handleCategoryUploadRemove(file, category) {
      if (category.images) {
        const index = category.images.indexOf(file.url)
        if (index !== -1) {
          category.images.splice(index, 1)
        }
      }
    },

    // 参数图片上传成功
    handleParameterUploadSuccess(response, parameter) {
      if (!parameter.images) {
        parameter.images = []
      }
      parameter.images.push(response.url)
    },

    // 参数图片删除
    handleParameterUploadRemove(file, parameter) {
      if (parameter.images) {
        const index = parameter.images.indexOf(file.url)
        if (index !== -1) {
          parameter.images.splice(index, 1)
        }
      }
    },

    // 关闭组件
    close() {
      this.$emit('close')
    },

    // 类别名称建议搜索
    querySearchCategory(queryString, cb) {
      const categoryOptions = this.categoryOptions
      const results = queryString
        ? categoryOptions.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
        : categoryOptions

      // 返回建议列表
      cb(results)
    },

    // 选择建议项处理
    handleSelectCategory(item) {
      console.log('选中类别:', item)
    },

    // 处理粘贴事件
    handlePaste(event, category) {
      console.log('粘贴事件触发')
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到图片URL:', textContent)
          // 直接添加URL到类别图片
          if (!category.images) {
            category.images = []
          }
          category.images.push(textContent)
          this.$message.success('图片URL已添加')

          // 如果类别已有ID且生产单已保存，自动保存类别
          if (category.id && this.productionOrderData.id) {
            console.log('类别已有ID，自动保存类别')
            this.handleSaveCategory(category)
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到图片文件:', blob)
            this.handleImageUpload(blob, category)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 检查字符串是否是图片URL
    isImageUrl(str) {
      // 检查是否是URL格式
      try {
        const url = new URL(str)
        // 检查URL是否指向图片
        const pathLower = url.pathname.toLowerCase()
        const isImageExt =
            pathLower.endsWith('.jpg') ||
            pathLower.endsWith('.jpeg') ||
            pathLower.endsWith('.png') ||
            pathLower.endsWith('.gif') ||
            pathLower.endsWith('.webp') ||
            pathLower.endsWith('.svg') ||
            pathLower.endsWith('.bmp')
        return isImageExt || /\.(jpg|jpeg|png|gif|webp|svg|bmp)/i.test(url.search)
      } catch (e) {
        return false
      }
    },

    // 处理拖拽事件
    handleDrop(event, category) {
      event.preventDefault()
      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的图片URL:', textContent)
          // 直接添加URL到类别图片
          if (!category.images) {
            category.images = []
          }
          category.images.push(textContent)
          this.$message.success('图片URL已添加')

          // 如果类别已有ID且生产单已保存，自动保存类别
          if (category.id && this.productionOrderData.id) {
            console.log('类别已有ID，自动保存类别')
            this.handleSaveCategory(category)
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            this.handleImageUpload(blob, category)
            foundImage = true
          }
        }

        if (!foundImage) {
          // 尝试从dataTransfer.files获取文件
          const files = data.files
          for (let i = 0; i < files.length; i++) {
            if (files[i].type.indexOf('image/') !== -1) {
              this.handleImageUpload(files[i], category)
              foundImage = true
            }
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    // 处理图片上传
    handleImageUpload(blob, category) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理图片...')
      const uploadId = `upload-${Date.now()}` // 创建唯一标识

      // 局部loading状态
      this.$set(category, 'imageLoading', true)

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 显示上传进度提示
          this.$notify({
            title: '上传中',
            message: '正在上传图片...',
            type: 'info',
            duration: 0,
            customClass: uploadId
          })

          // 调用上传接口
          UploadBase64Image({
            file_data: base64Data,
            directory_id: this.uploadDirectory || -1,
            keyword: this.uploadKeyword || ''
          })
            .then(response => {
              // 上传成功处理
              this.$notify.closeAll()
              this.$notify({
                title: '成功',
                message: '图片上传成功',
                type: 'success',
                duration: 2000
              })

              // 使用返回的URL更新类别图片
              if (!category.images) {
                category.images = []
              }
              category.images.push(response.data.url)

              // 如果类别已有ID且生产单已保存，自动保存类别
              if (category.id && this.productionOrderData.id) {
                console.log('类别已有ID，自动保存类别')
                this.handleSaveCategory(category)
              }

              // 关闭局部loading状态
              this.$set(category, 'imageLoading', false)
            })
            .catch(error => {
              // 上传失败处理
              this.$notify.closeAll()
              this.$notify({
                title: '错误',
                message: '图片上传失败: ' + (error.message || '未知错误'),
                type: 'error',
                duration: 3000
              })

              // 关闭局部loading状态
              this.$set(category, 'imageLoading', false)
            })
        } catch (err) {
          console.error('处理图片失败:', err)
          this.$message.error('图片处理失败')

          // 关闭局部loading状态
          this.$set(category, 'imageLoading', false)
        }
      }
      reader.onerror = () => {
        console.error('读取文件失败')
        this.$message.error('读取文件失败')

        // 关闭局部loading状态
        this.$set(category, 'imageLoading', false)
      }
      reader.readAsDataURL(blob)
    },

    // 触发文件输入
    triggerFileInput(category) {
      const input = this.$refs[`fileInput_${category.id || category.tempId}`][0]
      input.click()
    },

    // 处理文件变化
    handleFileChange(event, category) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.handleImageUpload(file, category)
      }
    },

    // 处理参数粘贴事件
    handleParameterPaste(event, parameter) {
      console.log('参数粘贴事件触发')
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到参数图片URL:', textContent)
          // 直接添加URL到参数图片
          if (!parameter.images) {
            parameter.images = []
          }
          parameter.images.push(textContent)
          this.$message.success('参数图片URL已添加')

          // 如果参数已有ID，查找所属类别并自动保存参数
          if (parameter.id) {
            // 查找参数所属的类别
            const category = this.findCategoryByParameter(parameter)
            if (category && category.id && this.productionOrderData.id) {
              console.log('参数已有ID，自动保存参数')
              this.handleSaveParameter(category, parameter)
            }
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到参数图片文件:', blob)
            this.handleParameterImageUpload(blob, parameter)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 处理参数拖拽事件
    handleParameterDrop(event, parameter) {
      event.preventDefault()
      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的参数图片URL:', textContent)
          // 直接添加URL到参数图片
          if (!parameter.images) {
            parameter.images = []
          }
          parameter.images.push(textContent)
          this.$message.success('参数图片URL已添加')

          // 如果参数已有ID，查找所属类别并自动保存参数
          if (parameter.id) {
            // 查找参数所属的类别
            const category = this.findCategoryByParameter(parameter)
            if (category && category.id && this.productionOrderData.id) {
              console.log('参数已有ID，自动保存参数')
              this.handleSaveParameter(category, parameter)
            }
          }

          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            this.handleParameterImageUpload(blob, parameter)
            foundImage = true
          }
        }

        if (!foundImage) {
          // 尝试从dataTransfer.files获取文件
          const files = data.files
          for (let i = 0; i < files.length; i++) {
            if (files[i].type.indexOf('image/') !== -1) {
              this.handleParameterImageUpload(files[i], parameter)
              foundImage = true
            }
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    // 处理参数图片上传
    handleParameterImageUpload(blob, parameter) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理参数图片...')
      const uploadId = `upload-${Date.now()}` // 创建唯一标识

      // 局部loading状态
      this.$set(parameter, 'imageLoading', true)

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 显示上传进度提示
          this.$notify({
            title: '上传中',
            message: '正在上传参数图片...',
            type: 'info',
            duration: 0,
            customClass: uploadId
          })

          // 调用上传接口
          UploadBase64Image({
            file_data: base64Data,
            directory_id: this.uploadDirectory || -1,
            keyword: this.uploadKeyword || ''
          })
            .then(response => {
              // 上传成功处理
              this.$notify.closeAll()
              this.$notify({
                title: '成功',
                message: '参数图片上传成功',
                type: 'success',
                duration: 2000
              })

              // 使用返回的URL更新参数图片
              if (!parameter.images) {
                parameter.images = []
              }
              parameter.images.push(response.data.url)

              // 如果参数已有ID，查找所属类别并自动保存参数
              if (parameter.id) {
                // 查找参数所属的类别
                const category = this.findCategoryByParameter(parameter)
                if (category && category.id && this.productionOrderData.id) {
                  console.log('参数已有ID，自动保存参数')
                  this.handleSaveParameter(category, parameter)
                }
              }

              // 关闭局部loading状态
              this.$set(parameter, 'imageLoading', false)
            })
            .catch(error => {
              // 上传失败处理
              this.$notify.closeAll()
              this.$notify({
                title: '错误',
                message: '参数图片上传失败: ' + (error.message || '未知错误'),
                type: 'error',
                duration: 3000
              })

              // 关闭局部loading状态
              this.$set(parameter, 'imageLoading', false)
            })
        } catch (err) {
          console.error('处理参数图片失败:', err)
          this.$message.error('参数图片处理失败')

          // 关闭局部loading状态
          this.$set(parameter, 'imageLoading', false)
        }
      }
      reader.onerror = () => {
        console.error('读取参数文件失败')
        this.$message.error('读取参数文件失败')

        // 关闭局部loading状态
        this.$set(parameter, 'imageLoading', false)
      }
      reader.readAsDataURL(blob)
    },

    // 触发参数文件输入
    triggerParameterFileInput(parameter) {
      const input = this.$refs[`paramFileInput_${parameter.id || parameter.$index}`][0]
      input.click()
    },

    // 处理参数文件变化
    handleParameterFileChange(event, parameter) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        this.handleParameterImageUpload(file, parameter)
      }
    },

    // 获取焦点
    focusPasteArea(event) {
      event.preventDefault()
    },

    // 预览图片
    previewImage(imageUrl) {
      this.dialogImageUrl = imageUrl
      this.dialogImageVisible = true
    },

    // 移除类别图片
    removeCategoryImage(category, index) {
      if (category.images) {
        category.images.splice(index, 1)
      }
    },

    // 移除参数图片
    removeParameterImage(parameter, index) {
      if (parameter.images) {
        parameter.images.splice(index, 1)
      }
    },

    // 处理保存参数
    handleSaveParameter(category, parameter) {
      // 验证类别是否有id
      if (!category.id) {
        this.$message.warning('类别还未保存，请先保存生产单')
        return
      }

      this.parameterLoading = true

      // 确保图片数组存在并且是字符串格式
      const images = parameter.images || []

      // 构建要保存的参数数据，使用通用参数API字段
      const paramData = {
        name: parameter.name,
        value: parameter.value,
        color: parameter.color || '#000000',
        unit: parameter.unit || '',
        price: parameter.price || 0.0,
        category_id: category.id, // 关联类别ID
        images: images.join(',') // 将图片URL数组转换为逗号分隔的字符串
      }

      this.$message.info('正在保存参数...')

      // 根据是否有ID决定是创建还是更新
      if (parameter.id) {
        // 调用API更新参数
        PutParameter(parameter.id, paramData)
          .then(response => {
            console.log('参数更新成功:', response.data)
            this.$notify({
              title: '成功',
              message: '参数更新成功',
              type: 'success',
              duration: 2000
            })
            this.parameterLoading = false
          })
          .catch(error => {
            console.error('参数更新失败:', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '参数更新失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      } else {
        // 调用API创建新参数
        PostParameter(paramData)
          .then(response => {
            console.log('新参数创建成功:', response.data)
            // 更新内存中的参数ID
            parameter.id = response.data.id
            this.$notify({
              title: '成功',
              message: '新参数创建成功',
              type: 'success',
              duration: 2000
            })
            this.parameterLoading = false
          })
          .catch(error => {
            console.error('新参数创建失败:', error)
            this.parameterLoading = false
            this.$notify.error({
              title: '错误',
              message: '新参数创建失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      }
    },

    // 处理保存类别
    handleSaveCategory(category) {
      // 验证对象ID是否存在
      if (!this.objectId) {
        this.$message.warning('关联对象还未保存，请先保存父对象')
        return
      }

      this.categoryLoading = true

      // 确保图片数组存在并且是字符串格式
      const images = category.images || []

      // 构建要保存的类别数据，使用通用类别API字段
      const categoryData = {
        name: category.name,
        content_type: this.modelType, // 模型类型
        object_id: this.objectId, // 关联对象ID
        images: images.join(','), // 将图片URL数组转换为逗号分隔的字符串
        position: category.position || 0, // 确保包含position字段
        is_shown: category.is_shown === undefined ? true : category.is_shown // 确保包含is_shown字段
      }

      this.$message.info('正在保存类别...')

      // 根据是否有ID决定是创建还是更新
      if (category.id) {
        // 调用API更新类别
        PutCategory(category.id, categoryData)
          .then(response => {
            console.log('类别更新成功:', response.data)
            this.$notify({
              title: '成功',
              message: '类别更新成功',
              type: 'success',
              duration: 2000
            })
            this.categoryLoading = false
            // 发射更新事件
            this.$emit('category-updated', category)
          })
          .catch(error => {
            console.error('类别更新失败:', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '类别更新失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      } else {
        // 调用API创建新类别
        PostCategory(categoryData)
          .then(response => {
            console.log('新类别创建成功:', response.data)
            // 更新内存中的类别ID
            category.id = response.data.id
            // 更新tempId
            delete category.tempId
            this.$notify({
              title: '成功',
              message: '新类别创建成功',
              type: 'success',
              duration: 2000
            })
            this.categoryLoading = false
            // 发射创建事件
            this.$emit('category-created', category)
          })
          .catch(error => {
            console.error('新类别创建失败:', error)
            this.categoryLoading = false
            this.$notify.error({
              title: '错误',
              message: '新类别创建失败: ' + (error.message || '未知错误'),
              duration: 3000
            })
          })
      }
    },

    // 查找参数所属的类别
    findCategoryByParameter(parameter) {
      if (!this.categories) {
        return null
      }

      for (const category of this.categories) {
        if (!category.parameters) {
          continue
        }

        const found = category.parameters.find(p => p === parameter || p.id === parameter.id)
        if (found) {
          return category
        }
      }

      return null
    },

    // 处理类别重新排序
    handleCategoryReorder() {
      // 更新所有类别的position值
      this.categories.forEach((category, index) => {
        category.position = index + 1
      })

      this.$message.success('类别顺序已更新，请保存以应用更改')

      // 如果对象已有ID，自动保存所有类别的排序
      if (this.objectId) {
        this.saveAllCategoriesPosition()
      }

      // 发射重排序事件
      this.$emit('categories-reordered', this.categories)
    },

    // 保存所有类别的排序
    saveAllCategoriesPosition() {
      if (!this.objectId) {
        this.$message.warning('请先保存关联对象')
        return
      }

      this.loading = true

      // 构建重新排序的数据
      const reorderData = this.categories.map((category, index) => ({
        id: category.id,
        position: index + 1
      })).filter(item => item.id) // 只包含已保存的类别

      if (reorderData.length === 0) {
        this.$message.warning('没有需要排序的类别')
        this.loading = false
        return
      }

      // 使用新的批量重排序API
      Reorder(reorderData)
        .then(() => {
          this.$notify({
            title: '成功',
            message: '类别排序已保存',
            type: 'success',
            duration: 2000
          })
          this.loading = false
          // 发射排序保存事件
          this.$emit('categories-reorder-saved', this.categories)
        })
        .catch(error => {
          console.error('保存类别排序失败:', error)
          this.$notify.error({
            title: '错误',
            message: '保存类别排序失败: ' + (error.message || '未知错误'),
            duration: 3000
          })
          this.loading = false
        })
    },

    // 打开Markdown编辑器
    openMarkdownEditor(parameter) {
      this.currentEditingParameter = parameter
      this.currentMarkdownContent = parameter.value || ''
      this.markdownDialogVisible = true
    },

    // 关闭Markdown编辑器
    closeMarkdownDialog() {
      this.markdownDialogVisible = false
      this.currentEditingParameter = null
    },

    // 确认Markdown编辑
    confirmMarkdownEdit() {
      if (this.currentEditingParameter) {
        this.currentEditingParameter.value = this.currentMarkdownContent

        // 如果参数已有ID且对象已保存，自动保存参数
        if (this.currentEditingParameter.id) {
          // 查找参数所属的类别
          const category = this.findCategoryByParameter(this.currentEditingParameter)
          if (category && category.id && this.objectId) {
            this.handleSaveParameter(category, this.currentEditingParameter)
          }
        }
      }
      this.closeMarkdownDialog()
    },
    isMarkdown(text) {
      if (!text) return false
      // 提高判断准确性，扩展检测更多Markdown特性
      return text.includes('#') ||
               text.includes('- ') ||
               text.includes('* ') ||
               text.includes('```') ||
               text.includes('> ') ||
               text.includes('|---|') ||
               text.includes('![') ||
               text.includes('[') ||
               /\[(.*?)\]\((.*?)\)/.test(text) || // 检测链接格式
               /^```[\s\S]*?```$/m.test(text) // 检测代码块
    },
    // 在methods部分添加处理参数值变化的方法
    handleParamValueChange(parameter) {
      // 如果参数已有ID，查找所属类别并自动保存参数
      if (parameter.id && this.objectId) {
        // 查找参数所属的类别
        const category = this.findCategoryByParameter(parameter)
        if (category && category.id) {
          // 为避免频繁保存，这里可以考虑使用节流或防抖
          // 简单实现：延迟1秒后保存
          if (this.saveParamTimeout) {
            clearTimeout(this.saveParamTimeout)
          }
          this.saveParamTimeout = setTimeout(() => {
            this.handleSaveParameter(category, parameter)
          }, 1000)
        }
      }
    },

    // 处理类别可见性变更
    handleCategoryVisibilityChange(category) {
      // 如果类别已有ID且对象已保存，自动保存类别
      if (category.id && this.objectId) {
        this.handleSaveCategory(category)

        // 显示状态变更提示
        const statusText = category.is_shown ? '显示' : '隐藏'
        this.$message({
          message: `类别"${category.name}"已设置为${statusText}`,
          type: 'success',
          duration: 1500
        })
      }

      // 发射可见性变更事件
      this.$emit('category-visibility-changed', category)
    }
  }
}
</script>

  <style scoped>
  .el-collapse {
    margin-top: 20px;
  }
  /* 针对自定义类名的样式规则 */
  .small-upload ::v-deep .el-upload--picture-card {
    width: 40px !important;
    height: 40px !important;
    line-height: 40px !important;
    font-size: 20px !important;
  }
  .el-upload--picture-card {
    width: 40px !important;
    height: 40px !important;
    line-height: 40px !important;
  }
  .form-item {
    margin-bottom: 15px;
  }
  .form-label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
  }
  .el-collapse-item >>> .el-collapse-item__header {
    background-color: #f0f9ff;
    padding: 12px;
    border-radius: 4px;
    font-weight: bold;
    font-size: 16px;
    border-left: 4px solid #409EFF;
    display: flex;
    align-items: center;
  }
  .el-collapse-item >>> .el-collapse-item__content {
    padding: 15px;
    background-color: #f7fbff;
    border: 1px solid #ebeef5;
    border-radius: 0 0 4px 4px;
    margin-bottom: 10px;
  }

  /* 类别区域样式 */
  .category-container {
    background-color: #f0f9ff;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 15px;
    border: 1px solid #d1e9ff;
  }

  /* 参数表格样式 */
  .parameters-table {
    background-color: #ffffff;
    border-radius: 4px;
    margin-top: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  }

  .parameters-table >>> .el-table__header-wrapper {
    background-color: #f5f7fa;
  }

  .parameters-table >>> .el-table th {
    background-color: #f5f7fa;
  }

  .parameters-table >>> .el-table--border {
    border: 1px solid #ebeef5;
  }

  /* 底部添加按钮样式 */
  .bottom-add-button {
    display: flex;
    justify-content: center;
    padding: 10px 0;
  }

  .bottom-add-button .el-button {
    padding: 8px 20px;
  }

  .bottom-add-category {
    display: flex;
    justify-content: center;
    margin: 15px 0;
  }

  .upload-container {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
  }
  .paste-area {
    padding: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    text-align: center;
    margin-bottom: 10px;
    cursor: pointer;
    background-color: #fafafa;
    transition: all 0.3s;
    min-height: 100px;
    outline: none;
  }
  .paste-area:hover, .paste-area:focus {
    border-color: #409EFF;
    background-color: #f5f7fa;
  }
  .paste-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 80px;
  }
  .paste-tip i {
    font-size: 24px;
    color: #909399;
    margin-bottom: 5px;
  }
  .parameter-paste-area {
    min-height: 50px;
    display: flex;
    flex-direction: column;
  }
  .parameter-paste-area .paste-tip {
    flex-direction: row;
    justify-content: center;
  }
  .parameter-paste-area .paste-tip i {
    font-size: 16px;
    margin-right: 5px;
    margin-bottom: 0;
  }
  .paste-images {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 5px;
  }
  .image-item {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
  }
  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .delete-icon {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    padding: 3px;
    color: #F56C6C;
    cursor: pointer;
  }
  .delete-icon:hover {
    background-color: rgba(255, 255, 255, 1);
    transform: scale(1.1);
  }
  .parameter-images {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
  .parameter-image-item {
    position: relative;
    width: 50px;
    height: 50px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
  }

  /* 优化表单样式 */
  .el-form-item {
    margin-bottom: 22px;
  }

  .el-form-item >>> .el-form-item__label {
    font-weight: 500;
    color: #606266;
  }

  .el-form-item >>> .el-input__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    transition: border-color 0.3s;
  }

  .el-form-item >>> .el-input__inner:hover {
    border-color: #c0c4cc;
  }

  .el-form-item >>> .el-input__inner:focus {
    border-color: #409EFF;
  }

  /* 分隔线样式 */
  .el-divider {
    margin: 24px 0;
  }

  .el-divider >>> .el-divider__text {
    background-color: #f5f7fa;
    color: #409EFF;
    font-weight: bold;
    padding: 0 20px;
  }

  /* 抽屉内容区域样式 */
  .el-drawer >>> .el-drawer__body {
    padding: 0;
  }

  .el-drawer >>> .el-drawer__header {
    margin-bottom: 0;
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    background-color: #f5f7fa;
  }

  /* 新添加的样式 */
  .drawer-content {
    padding: 20px;
    background-color: #fff;
  }

  .order-title {
    display: inline-block;
    font-size: 20px;
    font-weight: 600;
    margin-right: 10px;
    color: #303133;
  }

  .order-info {
    display: block;
    margin-top: 8px;
    color: #606266;
    font-size: 14px;
  }

  .info-item {
    margin-right: 15px;
  }

  .action-buttons {
    text-align: right;
    padding-top: 5px;
  }

  @media (max-width: 992px) {
    .action-buttons {
      text-align: left;
      margin-top: 15px;
    }
  }

  /* 美化表单样式 */
  .el-form {
    background-color: #f9fafc;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  /* 按钮样式优化 */
  .el-button {
    margin-left: 10px;
  }

  .el-button:first-child {
    margin-left: 0;
  }

  /* 抽屉全局样式 */
  .production-order-drawer >>> .el-drawer__header {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }

  /* 类别拖拽样式 */
  .category-drag-handle {
    cursor: move;
    margin-right: 8px;
    color: #909399;
  }

  .category-drag-handle:hover {
    color: #409EFF;
  }

  .category-position {
    font-size: 12px;
    color: #909399;
    margin-left: 10px;
  }

  /* Markdown编辑器相关样式 */
  .markdown-input-container {
    position: relative;
  }

  .markdown-icon {
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 18px;
    color: #409EFF;
    cursor: pointer;
    z-index: 1;
    padding: 4px;
    border-radius: 4px;
    background-color: rgba(255, 255, 255, 0.8);
    transition: all 0.3s;
  }

  .markdown-icon:hover {
    color: #66b1ff;
    background-color: rgba(240, 240, 240, 0.9);
    transform: scale(1.1);
  }

  /* 自定义v-md-editor样式 */
  ::v-deep .v-md-editor {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
  }

  ::v-deep .v-md-editor__toolbar {
    border-bottom: 1px solid #DCDFE6;
  }

  /* Markdown对话框样式 */
  .markdown-dialog {
    margin-top: 5vh !important;
  }

  ::v-deep .markdown-dialog .el-dialog__body {
    padding: 10px 20px;
  }

  ::v-deep .markdown-dialog .v-md-editor {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .markdown-preview-container {
    position: relative;
    width: 100%;
    margin-bottom: 10px;
  }

  /* Markdown预览样式 */
  .markdown-preview-container ::v-deep .v-md-editor {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview-wrapper {
    padding: 10px 15px;
    background-color: #ffffff;
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview p {
    margin: 8px 0;
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview h1,
  .markdown-preview-container ::v-deep .v-md-editor__preview h2,
  .markdown-preview-container ::v-deep .v-md-editor__preview h3 {
    margin-top: 12px;
    margin-bottom: 8px;
    color: #303133;
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview ul,
  .markdown-preview-container ::v-deep .v-md-editor__preview ol {
    padding-left: 20px;
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview code {
    background-color: #f5f7fa;
    padding: 2px 4px;
    border-radius: 3px;
    color: #E6A23C;
  }

  .markdown-preview-container ::v-deep .v-md-editor__preview pre {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    margin: 10px 0;
  }

  /* 确保编辑图标在预览模式下始终可见 */
  .markdown-preview-container .markdown-icon {
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10;
    background-color: rgba(255, 255, 255, 0.9);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  /* 图片AI按钮样式 */
  .image-ai-button {
    position: absolute;
    bottom: 5px;
    right: 5px;
    z-index: 5;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 4px;
    padding: 3px;
  }

  /* 参数图片AI按钮样式 */
  .parameter-image-item .image-ai-button {
    bottom: 3px;
    right: 3px;
    padding: 1px;
    transform: scale(0.8);
  }

  .parameter-image-item .image-ai-button ::v-deep .el-button--mini {
    padding: 4px 6px;
    font-size: 10px;
  }

  /* 版本对话框样式 */
  .version-actions {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }

  .version-current-tag {
    background-color: #67C23A;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 12px;
    margin-left: 5px;
  }

  .token-link {
    color: #409EFF;
    text-decoration: none;
    font-weight: 500;
  }

  .token-link:hover {
    color: #66b1ff;
    text-decoration: underline;
  }

  .token-time {
    font-size: 12px;
    color: #909399;
    margin-top: 3px;
  }

  .el-dropdown {
    display: inline-block;
  }

  /* 在小屏幕下优化下拉菜单显示 */
  @media (max-width: 768px) {
    .el-dropdown {
      display: block;
      margin-top: 10px;
    }
  }

  .logo-input-container {
    display: flex;
    flex-direction: column;
  }

  .logo-preview {
    display: flex;
    align-items: center;
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fafafa;
  }

  .logo-image {
    width: 80px;
    height: 80px;
    object-fit: contain;
    margin-right: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .logo-image:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .clear-logo-btn {
    color: #f56c6c;
  }
  </style>

